const { pair, head, tail, list, isNull, reverse, map } = require('./526');
const { isPair, print } = require('./527');
//作业1:reverseTree每次遇到分叉反一下
function reverse2(items) {
  return reverseIter(items);

  function reverseIter(items, result = null) {
    if (isNull(items)) return result;
    return reverseIter(tail(items), pair(result, reverse(head(items))));
  }
}
const reverseExample = list(list(1, 2), list(3, 4));
print(reverseExample);
// print(reverse2(reverse(reverseExample)));

//作业2:
// 练习：不使用map & 使用map
//不使用map
function squareTree(tree) {
  if (isNull(tree)) return null;
  if (!isPair(tree)) return tree ** 2;
  return pair(squareTree(head(tree)), squareTree(tail(tree)));
}
const kk = squareTree(reverseExample);
print(kk);

//使用map
function squareTree2(tree) {
  return map(tree, subTree =>
    isPair(subTree) ? squareTree(subTree) : subTree ** 2
  );
}

//
function treeMap(tree, fn) {
  if (isNull(tree)) return tree;
  return pair(head(tree), treeMap(tail(tree), fn));
}
function squareTreeWithTreeMap(tree) {
  return treeMap(tree, x => x ** 2);
}
// print(squareTreeWithTreeMap(reverseExample));
